package com.inifitness.common.xxl;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.ExchangeStrategies;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
import reactor.netty.http.client.HttpClient;

/**
 * TODO: (sunjinfeng 2024-06-06)
 *
 * @author sunjinfeng
 * @version 1.0.0
 * @since 2024-06-06 13:52
 */
@Component
@RequiredArgsConstructor
public class XxlJobClientConfig {

  private final XxlJobProperties xxlJobProperties;

  private static final int BYTE_COUNT = 16 * 1024 * 1024;
  @Bean
  public WebClient xxlJobWebClient() {
    // 创建一个HttpClient，并将其配置为使用代理
    HttpClient httpClient = HttpClient.create();

    return WebClient.builder()
        .clientConnector(new ReactorClientHttpConnector(httpClient))
        .exchangeStrategies(ExchangeStrategies.builder()
            .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(BYTE_COUNT))
            .build())
        .baseUrl(xxlJobProperties.getAdmin().getAddresses())
        .defaultCookie("XXL_JOB_LOGIN_IDENTITY",
            "7b226964223a312c22757365726e616d65223a2261646d696e222c2270617373776f7264223a226531306164633339343962613539616262653536653035376632306638383365222c22726f6c65223a312c227065726d697373696f6e223a6e756c6c7d")
        .build();
  }


  @Bean
  public HttpServiceProxyFactory httpServiceProxyFactory(WebClient xxlJobWebClient) {
    return HttpServiceProxyFactory.builderFor(WebClientAdapter.create(xxlJobWebClient))
        .build();
  }

  @SneakyThrows
  @Bean
  XxlJobClient xxlJobClient(WebClient xxlJobWebClient) {
    HttpServiceProxyFactory httpServiceProxyFactory =
        HttpServiceProxyFactory.builderFor(WebClientAdapter.create(xxlJobWebClient))
            .build();
    return httpServiceProxyFactory.createClient(XxlJobClient.class);
  }
}
